let COUNTER = 0;
let color = "{COOKIE_color}";
let joinTip = false;
let sendImg = false;
let roomCfg = null;
let host = null;
let connectError = false;
let connectCount = 0;
$(function () {
    Notification.requestPermission().then(function (p) {
        console.log(p);
    });

    loadRoomInfo();

    $("#message-type").click(function () {
        let a = $("#message-type")[0].checked;
        let b = $("#message-type-btn");
        if (a){
            b.text("图片消息");
            $("#sendTextDiv").slideUp();
            $("#sendPicDiv").slideDown();
        }else {
            b.text("文本消息");
            $("#sendPicDiv").slideUp();
            $("#sendTextDiv").slideDown();
        }
    });

    $("#send-message").click(function () {
        let m = $("#message");
        sendMessageText(m.val());
        m.val("");
    });

    $("#zoom_pic").click(function () {
        $(this).fadeOut();
    });

    document.getElementById("main-div").scrollTop = document.getElementById("main-div").scrollHeight;
    getMessage();
    $("#back").click(function () {
        window.open("./?/", "_self");
    });
    $("#sendMessage").click(function () {
        $("#input-message-text").val("");
        $("#input-message-pic").val("");
        $("#message-type-btn").text("文本消息");
        $("#message-type")[0].checked = false;
        $("#sendPicDiv").slideUp();
        $("#sendTextDiv").slideDown();
        $("#open-modal-send").click();
    });

    $("#add-ban-btn").click(function () {
        $("#ban-id").val("");
        $("#add-ban").slideDown();
    });
    $("#add-ban-save").click(function () {
        $("#add-ban").slideUp();
        let id = $("#ban-id").val();
        $.post("./?/ban",{
            id:id
        },function (text){
            console.log(text);
            location.reload();
        });
    });
    $("#add-ban-cancel").click(function () {
        $("#add-ban").slideUp();
        $("#ban-id").val("");
    });

    $("#manage-ok").click(function () {
        let canSend = $("#manage-send-pic")[0].checked?"yes":"no";
        let joinTip = $("#manage-join-tip")[0].checked?"yes":"no";
        $.post("./?/setRoomCfg",{
            canSend:canSend,
            joinTip:joinTip
        },function (text) {
            console.log(text);
            location.reload();
        });
    });

    $("#sendPicBtn").click(function () {
        $("#input-message-pic").click();
    });
    $("#input-message-pic").change(function () {
        sendMessagePic();
    });

    $("#message").keydown(function (e) {
        if (e.keyCode === 13 && e.ctrlKey){
            $("#send-message").click();
        }
    });

    let emojiList = ``;
    for (let i = 1;i <= 17;i++){
        let x = `<a class="btn btn-flat btn-sm"><span class="emoji-${i}" onclick="insertEmoji(\`emoji-${i}\`)"></span></a>`;
        emojiList += x;
    }
    $("#emoji-list").html(emojiList);
});

function loadRoomInfo(){
    $.post("./?/getRoomInfo",{},function (text) {
        roomCfg = JSON.parse(text);
        sendImg = roomCfg.sendPic === "yes";
        joinTip = roomCfg.joinTip === "yes";
        if (!sendImg){
            $("#message-type,#message-type-btn").attr("disabled","disabled");
        }
        $("#adminId").text(roomCfg.admin);
    });
    $.post("./?/getHost",{},function (text) {
        host = text;
        if (!(roomCfg.admin.toString() === host.toString() || isSAdmin)){
            $("#manage-room").remove();
        }else {
            $("#manage-send-pic")[0].checked = roomCfg.sendPic === "yes";
            $("#manage-join-tip")[0].checked = roomCfg.joinTip === "yes";
            if (roomCfg.sendPic !== "yes") {
                $("#sendPicBtn").remove();
            }
            let content = ``;
            for (const k in roomCfg.banList) {
                let v = roomCfg.banList[k];
                let t = v.time;
                content += `<tr><td>${t}</td><td>${k}</td><td><button class="btn btn-sm waves-button waves-effect waves-light" onclick="unban(\'`+k+`\')">解除禁言</button></td></tr>`;
            }
            $("#ban-list-main").html(content);
            loadColor();
        }
    });

}

function getCounter() {
    try {
        $.ajax({
            url: "./?/getCounter",
            method: "POST",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            error:function () {
                if (connectError){
                    connectCount++;
                }
                connectError=true;
                $(".float-message").html(`与消息服务器通信故障，正在尝试重连：第${Math.round(connectCount/2)}次<br>请不要刷新页面`).fadeIn();
                setTimeout(getCounter,1000);
            },
            success:function (text) {
                if (connectError){
                    connectError=false;
                    connectCount=0;
                    $(".float-message").text("消息服务器重连成功！");
                    console.clear();
                    setTimeout(function () {
                        $(".float-message").fadeOut();
                    },500);
                }
                if (text !== COUNTER) {
                    COUNTER = text;
                    toast("收到新消息！");
                    document.title="收到新消息！";
                    let notification = new Notification("收到新消息！",{
                        body:"快去查看吧！",
                        icon: "?/file&name=logo.png"
                    });
                    setTimeout(function (){document.title="聊天室"},2000);
                    getMessage();
                } else {
                    setTimeout(getCounter, 200);
                }
            },

        });

        /*$.post("./?/getCounter", {}, function (text) {

        });*/
    }catch{}
}

function getMessage() {
    $.post("./?/getMessage", {}, function (text) {
        let content = "";
        let data = JSON.parse(text);
        for (const i in data) {
            let v = data[i];
            if (v.indexOf("system-message")===-1) {
                content += `<p class="message">${v}</p>`;
            }else {
                content += `<p class="message system-message">${v}</p>`;
            }
        }
        $("#main-div").html(content);
        $("p.message>img").bind("click",function () {
            $("#zoom_pic>img").attr("src",$(this).attr("src"));
            $("#zoom_pic").css("opacity",100).fadeIn();
        });
        document.getElementById("main-div").scrollTop = document.getElementById("main-div").scrollHeight;
        getCounter();
    });


}

function sendMessageText(message) {
    if (!message) {
        return;
    }
    $.post("./?/sendMessage", {message: message}, function (text) {
        if (text === "ban") {
            /*// toast("你已被禁言！");*/
            floatMessage("您已被禁言！");
        }
    });
}
function sendMessagePic() {
    $.ajax({
        url:"./?/sendPic",
        type:"POST",
        cache:false,
        data:new FormData($("#upload-form")[0]),
        processData:false,
        contentType:false,
        dataType:"json",
        success:function (data) {
            console.log(data);
            location.reload();
        },
        error:function (e) {
            console.log(e);
            /*floatMessage("图片发送失败");*/
        }
    });
}
function unban(id) {
    $.post("./?/unban",{
        id:id
    },function (text) {
        console.log(text);
        location.reload();
    });
}
function dialog(title,message) {
    $("#modal-dialog-title").text(title);
    $("#modal-dialog-message").text(message);
    $("#open-modal-dialog").click();
}
function toast(message) {
    let a = $("#showToast");
    a.attr("data-original-title",message);
    a.click();
}
function floatMessage(message) {
    $(".float-message").text(message).fadeIn();
    setTimeout(function () {
        $(".float-message").fadeOut();
    },1500);
}
function insertEmoji(emoji) {
    let m = $("#message");
    m.val(m.val()+`#${emoji}#`);
}